package com.techsen.tsweb.sys.web.controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.techsen.tsweb.core.util.SubjectUtil;
import com.techsen.tsweb.sys.domain.Menu;
import com.techsen.tsweb.sys.domain.User;
import com.techsen.tsweb.sys.service.MenuService;
import com.techsen.tsweb.sys.service.UserService;

@Controller
public class LoginController {

    @Resource
    private UserService userService;
    
    @Resource
    private MenuService menuService;

    /**
     * 进入登录界面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    /**
     * 处理登录请求
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(User user, boolean rememberMe) {
        if (user != null) {
            UsernamePasswordToken token = new UsernamePasswordToken(
                    user.getLoginAct(), user.getLoginPwd());
            token.setRememberMe(rememberMe);
            SubjectUtil.getSubject().login(token);
            return "redirect:/index";
        }
        return "redirect:/login";
    }

    /**
     * 注销
     */
    @RequestMapping("/logout")
    public String logout() {
        SubjectUtil.getSubject().logout();
        return "redirect:/login";
    }

    /**
     * 跳转到首页
     */
    @RequestMapping(value = { "/", "/index" })
    public String index(Model model) {
        List<Menu> menus = this.menuService.findAll();
        model.addAttribute("menus", menus);
        return "index";
    }

}
